﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using HTspcAppProject.Model;
using HTDAL.HTSPC_DBDataSetTableAdapters;
using System.Runtime.InteropServices;

namespace HTspcAppProject
{
    public partial class Form1 : Form
    {
        private int deviceNum;
        private char[] deviceState;
        private List<Label> label_device;
        private List<PictureBox> picture_device;
        private List<Device> all_device;

        private List<Label> label_runtime;
        private List<Label> label_stoptime;
        private List<Label> label_OEE;
        private List<Label> label_produceBatch;
        private List<Label> label_checkBatch;
        private List<Panel> panels;
        

        private List<Label> runtime;
        private List<Label> stoptime;
        private List<Label> OEE;
        private List<Label> produceBatch;
        private List<Label> checkBatch;

        private List<Button> buttons;

        private List<Form2> lform2 = new List<Form2>();


        private int left_width = 70;
        private int each_width = 160;
        private int label_width = 100;
        //private int label_left = 35;
        //private int value_left = 120;

        //后室温度报警标记
        Dictionary<string, bool> HsTagDict = new Dictionary<string, bool>();
        //油槽温度报警标记
        Dictionary<string, bool> YcTagDict = new Dictionary<string, bool>();

        private Timer time;

        public Timer Time
        {
            get { return time; }
            set { time = value; }
        }

        CommonClass comm = new CommonClass(); //指令集初始化

        public Form1()
        {
            FormLoginProgress flp = new FormLoginProgress();
            flp.Show();
            flp.Refresh();
            flp.StartPosition = FormStartPosition.CenterScreen;
            flp.TopMost = true;
            flp.pgBar.Value = 20;
            InitializeComponent();
            flp.pgBar.Value = 30;
            flp.Refresh();
            InitlClass initl = new InitlClass();
            flp.pgBar.Value = 60;
            flp.Refresh();
            //先启动通信进程，获取设备数量和相关信息
            //假设通信进程为Communication，返回数据信息DeviceInfo类型数据
            //deviceNum = DeviceInfo.number;
            //deviceState是bool型数组，0表示停机，1表示工作
            deviceNum = 7;
            //假设一个设备初始状态
            deviceState = new char[deviceNum];
            for (int i = 0; i < deviceNum; i++)
            {
                    deviceState[i] = 'N';
            }
            //根据设备数，动态设置屏幕宽度。注意：如果太大，要做滚动条处理
            //this.Width = each_width * deviceNum + left_width;
            this.WindowState = FormWindowState.Maximized;
            //this.MinimumSize = new Size(each_width * deviceNum + left_width, 590);
            

            label_device = new List<Label>();
            picture_device = new List<PictureBox>();
            all_device = new List<Device>();

            label_runtime = new List<Label>();
            label_stoptime = new List<Label>();
            label_OEE = new List<Label>();
            label_produceBatch = new List<Label>();
            label_checkBatch = new List<Label>();
            panels = new List<Panel>();

            runtime = new List<Label>();
            stoptime = new List<Label>();
            OEE = new List<Label>();
            produceBatch = new List<Label>();
            checkBatch = new List<Label>();

            buttons = new List<Button>();
            flp.pgBar.Value = 80;
            flp.Refresh();

            time = new Timer();
            //定义从主界面跳转到设备的时间间隔
            time.Interval = CommonClass.Jumpt;
            //time.Enabled = true;

            time.Tick +=new EventHandler(time_Tick);
            //子窗体生成
            for (int i = 0; i < CommonClass.devDtList.Rows.Count; i++)
            {
                lform2.Add(new Form2(i + 1, this, false));
            }
            flp.pgBar.Value = 100;
            flp.Refresh();
            flp.Close();

            //叶岍 20131021 更新设备列表时间线程
            System.Timers.Timer thrTimer = new System.Timers.Timer();
            thrTimer.Elapsed += new System.Timers.ElapsedEventHandler(DevInfoInit);
            thrTimer.Interval = 3000;
            thrTimer.Start();
        }

        int jumpIndex = 0;
        private void time_Tick(Object sender, EventArgs e)
        {
            //time.Enabled = false;
            //this.Hide();
            //Form2 form2 = new Form2(1, this,true);
            //form2.Show();
            if (jumpIndex > 0)
            {
                if (!lform2[jumpIndex - 1].jumpEnable)
                {
                    time.Stop();
                    lform2[jumpIndex - 1].jumpEnable = true;
                    stm_autojump.CheckState = CheckState.Unchecked;
                    jumpIndex = 0;
                    return;
                }
                lform2[jumpIndex - 1].Hide();
                if (jumpIndex >= CommonClass.devDtList.Rows.Count)
                {
                    time.Stop();
                    time.Interval = CommonClass.Jumpt;
                    jumpIndex = 0;
                    time.Start();
                    return;
                }
            }
            lform2[jumpIndex].Show();
            jumpIndex++;
            time.Interval = CommonClass.Jumptc;
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            //设置某些元素的位置
            each_width = (this.Width - left_width) / deviceNum;
            label_title.Text = CommonClass.mTile;
            //label_title.Location = new System.Drawing.Point(this.Width / 2 - label_title.Size.Width / 2, 10);
            panel1.Location = new System.Drawing.Point(0, 0);
            //动态创建显示设备
            int currentDeviceNum;
            for (currentDeviceNum = 0; currentDeviceNum < deviceNum; currentDeviceNum++)
            {
                string devNm = "";
                if (currentDeviceNum < CommonClass.devDtList.Rows.Count)
                {
                    devNm = Convert.ToString(CommonClass.devDtList.Rows[currentDeviceNum]["devNm"]);
                }
                CreateDeviceLabel(currentDeviceNum, devNm);
                CreateDevicePic(currentDeviceNum);
                CreateDevice(currentDeviceNum);
                CreateDeviceData(currentDeviceNum);
            }

            this.FormBorderStyle = FormBorderStyle.None;

            timer1.Enabled = true; //通讯开始

            //Timer time_c = new Timer();
            //time_c.Enabled = false;
            //time_c.Interval = 10000;
            //time_c.Tick +=  new EventHandler(time_c_Tick);

            time.Enabled = true;

            
        }


        private void DevInfoInit(object source, System.Timers.ElapsedEventArgs e)
        {
            lock (CommonClass.devDtList)
            {
                ht_devSetTableAdapter devSetTa = new ht_devSetTableAdapter();
                CommonClass.devDtList = devSetTa.GetData();

            }

        }

        private void time_c_Tick(object sender, EventArgs e)
        {
            SetValue(1, all_device[0].RunTime + 1, all_device[0].StopTime + 1, all_device[0].OEE + 1, all_device[0].ProduceBatch + 1, all_device[0].CheckBatch + 1);
            SetValue(2, all_device[1].RunTime + 2, all_device[1].StopTime + 1, all_device[1].OEE + 1, all_device[1].ProduceBatch + 1, all_device[1].CheckBatch + 1);
            SetValue(3, all_device[2].RunTime + 1, all_device[2].StopTime + 2, all_device[2].OEE + 1, all_device[2].ProduceBatch + 1, all_device[2].CheckBatch + 1);
            SetValue(4, all_device[3].RunTime + 1, all_device[3].StopTime + 1, all_device[3].OEE + 2, all_device[3].ProduceBatch + 1, all_device[3].CheckBatch + 1);
            SetValue(5, all_device[4].RunTime + 1, all_device[4].StopTime + 1, all_device[4].OEE + 1, all_device[4].ProduceBatch + 2, all_device[4].CheckBatch + 1);
            SetValue(6, all_device[5].RunTime + 1, all_device[5].StopTime + 1, all_device[5].OEE + 1, all_device[5].ProduceBatch + 1, all_device[5].CheckBatch + 2);
            SetValue(7, all_device[6].RunTime + 3, all_device[6].StopTime + 1, all_device[6].OEE + 2, all_device[6].ProduceBatch + 1, all_device[6].CheckBatch + 1);

        }

        private void CreateDeviceLabel(int currentDeviceNum,string devNm)
        {
            Label label_temp = new Label();

            label_temp.Text = devNm;
            label_temp.AutoSize = true;
            label_temp.Font = new System.Drawing.Font("微软雅黑", 15F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
            label_temp.Location = new System.Drawing.Point(left_width + each_width * currentDeviceNum-15, 115);
            label_temp.Name = "device_label" + (currentDeviceNum + 1);
            label_temp.Size = new System.Drawing.Size(label_width, 27);
            label_temp.Anchor = AnchorStyles.None;
            label_temp.TextAlign = ContentAlignment.MiddleCenter;
            //label_temp.Text = "设备 #" + (currentDeviceNum + 1);

            label_device.Add(label_temp);
            this.Controls.Add(label_device[currentDeviceNum]);
        }

        private void CreateDevicePic(int currentDeviceNum)
        {
            PictureBox picture_temp = new PictureBox();

            if(deviceState[currentDeviceNum]=='1')
                picture_temp.Image = global::HTspcAppProject.Properties.Resources.device_on;
            else if (deviceState[currentDeviceNum] == '0')
                picture_temp.Image = global::HTspcAppProject.Properties.Resources.device_off;
            else
                picture_temp.Image = global::HTspcAppProject.Properties.Resources.device_leave;  //叶岍 2013-10-12更新

            picture_temp.Location = new System.Drawing.Point(left_width + each_width * currentDeviceNum, 160);
            picture_temp.Name = "pictureBox" + (currentDeviceNum + 1);
            picture_temp.Size = new System.Drawing.Size(label_width, 78);
            picture_temp.TabStop = false;

            picture_device.Add(picture_temp);
            this.Controls.Add(picture_device[currentDeviceNum]);

            picture_device[currentDeviceNum].Click += new System.EventHandler(this.Device_Click);//添加Click事件
        }

        private void CreateDevice(int currentDeviceNum)
        {
            Device device_temp = new Device(currentDeviceNum, deviceState[currentDeviceNum]);
            all_device.Add(device_temp);
        }

        private void CreateDeviceData(int currentDeviceNum)
        {
            //为每个设备创建一个panel，增加可视性
            Panel panel_temp = new Panel();

            panel_temp.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
            panel_temp.Location = new System.Drawing.Point(20 + each_width * currentDeviceNum, 110);
            panel_temp.Name = "panel" + (currentDeviceNum + 1);
            panel_temp.Size = new System.Drawing.Size((this.Width - 30) / deviceNum, 510);

            panels.Add(panel_temp);
            this.Controls.Add(panels[currentDeviceNum]);
            //创建固定标签
            Label runtime_temp = new Label();

            runtime_temp.Text = "运行时间：run time";
            runtime_temp.AutoSize = false;
            runtime_temp.Font = new System.Drawing.Font("微软雅黑", 11F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
            runtime_temp.Location = new System.Drawing.Point(15, 150);
            runtime_temp.Name = "runtime_label" + (currentDeviceNum + 1);
            runtime_temp.Size = new System.Drawing.Size(85, 40);

            label_runtime.Add(runtime_temp);
            //this.Controls.Add(label_runtime[currentDeviceNum]);
            panels[currentDeviceNum].Controls.Add(label_runtime[currentDeviceNum]);

            Label stoptime_temp = new Label();

            stoptime_temp.Text = "停机时间：stop time";
            stoptime_temp.AutoSize = false;
            stoptime_temp.Font = new System.Drawing.Font("微软雅黑", 11F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
            stoptime_temp.Location = new System.Drawing.Point(15, 210);
            stoptime_temp.Name = "stoptime_label" + (currentDeviceNum + 1);
            stoptime_temp.Size = new System.Drawing.Size(85, 40);

            label_stoptime.Add(stoptime_temp);
            panels[currentDeviceNum].Controls.Add(label_stoptime[currentDeviceNum]);

            Label OEE_temp = new Label();

            OEE_temp.Text = "OEE：";
            OEE_temp.AutoSize = false;
            OEE_temp.Font = new System.Drawing.Font("微软雅黑", 11F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
            OEE_temp.Location = new System.Drawing.Point(15, 270);
            OEE_temp.Name = "OEE_label" + (currentDeviceNum + 1);
            OEE_temp.Size = new System.Drawing.Size(85, 40);
            OEE_temp.TextAlign = ContentAlignment.MiddleLeft;

            label_OEE.Add(OEE_temp);
            panels[currentDeviceNum].Controls.Add(label_OEE[currentDeviceNum]);

            Label produceBatch_temp = new Label();

            produceBatch_temp.Text = "计划批次：plan";
            produceBatch_temp.AutoSize = false;
            produceBatch_temp.Font = new System.Drawing.Font("微软雅黑", 11F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
            produceBatch_temp.Location = new System.Drawing.Point(15, 330);
            produceBatch_temp.Name = "produceBatch_label" + (currentDeviceNum + 1);
            produceBatch_temp.Size = new System.Drawing.Size(85, 40);

            label_produceBatch.Add(produceBatch_temp);
            panels[currentDeviceNum].Controls.Add(label_produceBatch[currentDeviceNum]);

            Label checkBatch_temp = new Label();

            checkBatch_temp.Text = "生产批次：Done";
            checkBatch_temp.AutoSize = false;
            checkBatch_temp.Font = new System.Drawing.Font("微软雅黑", 11F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
            checkBatch_temp.Location = new System.Drawing.Point(15, 390);
            checkBatch_temp.Name = "checkBatch_label" + (currentDeviceNum + 1);
            checkBatch_temp.Size = new System.Drawing.Size(85, 40);

            label_checkBatch.Add(checkBatch_temp);
            panels[currentDeviceNum].Controls.Add(label_checkBatch[currentDeviceNum]);

            //创建动态显示数据指标
            Label runtime_value = new Label();

            runtime_value.Text = all_device[currentDeviceNum].RunTime + " h";
            runtime_value.Font = new System.Drawing.Font("微软雅黑", 11F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
            runtime_value.Location = new System.Drawing.Point(100, 150);
            runtime_value.Name = "runtime_value" + (currentDeviceNum + 1);
            runtime_value.Size = new System.Drawing.Size(70, 27);
            runtime_value.TextAlign = ContentAlignment.MiddleCenter;

            runtime.Add(runtime_value);
            panels[currentDeviceNum].Controls.Add(runtime[currentDeviceNum]);
            //
            Label stoptime_value = new Label();

            stoptime_value.Text = all_device[currentDeviceNum].StopTime + " h";
            stoptime_value.Font = new System.Drawing.Font("微软雅黑", 11F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
            stoptime_value.Location = new System.Drawing.Point(100, 210);
            stoptime_value.Name = "stoptime_value" + (currentDeviceNum + 1);
            stoptime_value.Size = new System.Drawing.Size(70, 27);
            stoptime_value.TextAlign = ContentAlignment.MiddleCenter;

            stoptime.Add(stoptime_value);
            panels[currentDeviceNum].Controls.Add(stoptime[currentDeviceNum]);
            //
            Label OEE_value = new Label();

            OEE_value.Text = all_device[currentDeviceNum].OEE + " %";
            OEE_value.Font = new System.Drawing.Font("微软雅黑", 11F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
            OEE_value.Location = new System.Drawing.Point(100, 278);
            OEE_value.Name = "OEE_value" + (currentDeviceNum + 1);
            OEE_value.Size = new System.Drawing.Size(70, 27);
            OEE_value.TextAlign = ContentAlignment.MiddleCenter;

            OEE.Add(OEE_value);
            panels[currentDeviceNum].Controls.Add(OEE[currentDeviceNum]);
            //
            Label produceBatch_value = new Label();

            produceBatch_value.Text = all_device[currentDeviceNum].ProduceBatch + " 次";
            produceBatch_value.Font = new System.Drawing.Font("微软雅黑", 11F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
            produceBatch_value.Location = new System.Drawing.Point(100, 390);
            produceBatch_value.Name = "produceBatch_value" + (currentDeviceNum + 1);
            produceBatch_value.Size = new System.Drawing.Size(70, 27);
            produceBatch_value.TextAlign = ContentAlignment.MiddleCenter;

            produceBatch.Add(produceBatch_value);
            panels[currentDeviceNum].Controls.Add(produceBatch[currentDeviceNum]);
            //
            Label checkBatch_value = new Label();

            checkBatch_value.Text = all_device[currentDeviceNum].CheckBatch + " 次";
            checkBatch_value.Font = new System.Drawing.Font("微软雅黑", 11F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
            checkBatch_value.Location = new System.Drawing.Point(100, 330);
            checkBatch_value.Name = "checkBatch_value" + (currentDeviceNum + 1);
            checkBatch_value.Size = new System.Drawing.Size(70, 27);
            checkBatch_value.TextAlign = ContentAlignment.MiddleCenter;

            checkBatch.Add(checkBatch_value);
            panels[currentDeviceNum].Controls.Add(checkBatch[currentDeviceNum]);

            //创建重置按钮
            Button but = new Button();

            but.Text = "重置/Reset";
            but.AutoSize = false;
            but.Font = new System.Drawing.Font("微软雅黑", 11F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
            but.Location = new System.Drawing.Point(36, 450);
            but.Name = "Button" + (currentDeviceNum + 1);
            but.Size = new System.Drawing.Size(110, 35);
            but.FlatStyle = FlatStyle.Flat;
            buttons.Add(but);

            panels[currentDeviceNum].Controls.Add(buttons[currentDeviceNum]);
            buttons[currentDeviceNum].Click += new System.EventHandler(this.Button_Click);//添加Click事件

            //设置布局方式
            //buttons[currentDeviceNum].Anchor = ((AnchorStyles)((AnchorStyles.Left | AnchorStyles.Right | AnchorStyles.Top | AnchorStyles.Bottom)));

        }

        private void Device_Click(object sender, EventArgs e)
        {
            PictureBox pic = sender as PictureBox;

            int length = pic.Name.Length;
            int deviceNum = Convert.ToInt32(pic.Name.Substring(length - 1, 1));
            stm_autojump.CheckState = CheckState.Unchecked;
            //this.Hide();
            //Form2 form2 = new Form2(deviceNum, this,false);
            //form2.ShowDialog();
            lform2[deviceNum - 1].Show();

        }

        private void Button_Click(object sender, EventArgs e)
        {
            MessageBoxButtons messButton = MessageBoxButtons.OKCancel;
            DialogResult dr = MessageBox.Show("确定要重置吗?", "重置月检次数", messButton);
            if (dr == DialogResult.OK)
            {
                Button but = sender as Button;

                int length = but.Name.Length;
                int deviceNum = Convert.ToInt32(but.Name.Substring(length - 1, 1));

                all_device[deviceNum - 1].CheckBatch = 0;
                checkBatch[deviceNum - 1].Text = "0" + "次";
                string devNm = Convert.ToString(CommonClass.devDtList.Rows[deviceNum-1]["devNm"]);

                CommonClass.stDict[devNm].chktms = 0;
            }
            System.Console.WriteLine("width: "+this.Width);
        }

        private void Form1_Resize(object sender, EventArgs e)
        {
            //根据窗体大小，调整空间位置

        }

        private void SetValue(int deviceNum, double runtime,double stoptime, float oee, int produceBatch, int checkBatch)
        {
            all_device[deviceNum-1].SetValue(runtime, stoptime, oee, produceBatch, checkBatch);
            this.runtime[deviceNum-1].Text = all_device[deviceNum - 1].RunTime.ToString("N1") + "H";
            this.stoptime[deviceNum-1].Text = all_device[deviceNum - 1].StopTime.ToString("N1") + "H";
            this.OEE[deviceNum-1].Text = all_device[deviceNum - 1].OEE.ToString("N1") + "%";
            this.produceBatch[deviceNum-1].Text = all_device[deviceNum - 1].ProduceBatch + "次";
            this.checkBatch[deviceNum-1].Text = all_device[deviceNum - 1].CheckBatch + "次";

            if (deviceState[deviceNum-1]=='1')
                picture_device[deviceNum-1].Image = global::HTspcAppProject.Properties.Resources.device_on;
            else if (deviceState[deviceNum - 1] == '0')
                picture_device[deviceNum-1].Image = global::HTspcAppProject.Properties.Resources.device_off;
            else
                picture_device[deviceNum - 1].Image = global::HTspcAppProject.Properties.Resources.device_leave;

        }

        //
        DataPacket dataPk = new DataPacket();

        /// <summary>
        /// 数据采集
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void timer1_Tick(object sender, EventArgs e)
        {
            try
            {
                if (backgroundWorker1.IsBusy)
                {
                    BackgroundWorker backgroundWorkerF = new BackgroundWorker();
                    backgroundWorkerF.DoWork += new System.ComponentModel.DoWorkEventHandler(this.backgroundWorker1_DoWork);
                    backgroundWorkerF.RunWorkerCompleted += new System.ComponentModel.RunWorkerCompletedEventHandler(this.backgroundWorker1_RunWorkerCompleted);
                    backgroundWorkerF.RunWorkerAsync();
                }
                else
                {
                    backgroundWorker1.RunWorkerAsync();
                }
                if (!msgTag)
                {
                    Application.Restart();
                    Application.Exit();
                }
                int devIndex = 0;
                foreach (DataRow dr in CommonClass.devDtList.Rows)
                {
                    string devNm = (string)dr["devNm"];

                    if (CommonClass.pmDict.Keys.Contains(devNm))
                    {
                        ht_pmmr pmmr = CommonClass.pmDict[devNm];
                        ht_stmr stmr = CommonClass.stDict[devNm];
                        SetValue(devIndex + 1, Math.Round((stmr.onRt / (double)3600),1), Math.Round((stmr.offRt / (double)3600),1),
                            Convert.ToSingle(stmr.OEE), stmr.prdbn, stmr.chktms);
                    }
                    else
                    {
                        deviceState[devIndex] = 'N';
                        SetValue(devIndex + 1, 0, 0, 0, 0, 0);

                    }
                    devIndex++;
                }
            }
            catch (Exception ex)
            {
                CommonClass.LogError(ex.ToString());
            }
            
        }

        bool DataTag = true;
        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
          DataTag = dataPk.DevDataGet();

            if (CommonClass.devCount != CommonClass.devDtList.Rows.Count)
            {
                if (msgTag)
                {
                    timer1.Stop();
                    msgTag = false;
                    stm_autojump.CheckState = CheckState.Unchecked;
                    if (MessageBox.Show("设备设置发生变化，为保证数据准确请重启本软件！", "警告",
                        MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == System.Windows.Forms.DialogResult.Yes)
                    {
                        
                    }
                    else { msgTag = true; }
                    timer1.Start();
                }
            }

            if (DataTag)
            {
                DataToView();
            }
            else
            {
                int devIndex = 0;
                foreach (DataRow dr in CommonClass.devDtList.Rows)
                {
                    string devNm = (string)dr["devNm"];
                    if (CommonClass.pmDict.Keys.Contains(devNm))
                    {
                        ht_pmmr pmmr = CommonClass.pmDict[devNm];
                        ht_stmr stmr = CommonClass.stDict[devNm];
                        deviceState[devIndex] = 'N';
                        stmr.powerSt = "N";
                        pmmr.st = "N";
                    }
                    devIndex++;
                }
            }
        }

        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            ((BackgroundWorker)sender).Dispose();
        }

        //bool prdTag = true;
        bool msgTag = true;
        //是否记批标识
        Dictionary<string, bool> prdTagDict = new Dictionary<string, bool>();
        /// <summary>
        /// 主界面显示及更新处理
        /// </summary>
        object lockObj = new object();
        private void DataToView()
        {
            int devIndex = 0;
            foreach (DataRow dr in CommonClass.devDtList.Rows)
            {
                string devNm = (string)dr["devNm"];

                if (CommonClass.pmDict.Keys.Contains(devNm))
                {
                    ht_pmmr pmmr = CommonClass.pmDict[devNm];
                    ht_stmr stmr = CommonClass.stDict[devNm];
                    lock (lockObj)
                    {
                    if (!prdTagDict.Keys.Contains(devNm))
                    {
                        prdTagDict.Add(devNm, true);
                    }
                    if (!YcTagDict.Keys.Contains(devNm))
                    {
                        YcTagDict.Add(devNm, true);
                    }
                    if (!HsTagDict.Keys.Contains(devNm))
                    {
                        HsTagDict.Add(devNm, true);
                    }
                    }
                    pmmr.cpSet = Convert.ToDouble(dr["cpSet"]);
                    pmmr.gyid = Convert.ToString(dr["gyid"]);
                    pmmr.hswdSet = Convert.ToDouble(dr["hswdSet"]);
                    pmmr.ycwdSer = Convert.ToDouble(dr["ycwdSer"]);
                    if (Convert.ToString(dr["res"]) == "1")
                    {
                        ht_devSetTableAdapter devSetTa = new ht_devSetTableAdapter();
                        devSetTa.UpdateResReset(devNm);
                        stmr.chktms = 0;
                    }
                    stmr.devNm = pmmr.devNm;
                    if (stmr.dt.Year != DateTime.Now.Year || stmr.dt.Month != DateTime.Now.Month)
                    {
                        try
                        {
                            ht_stlogTableAdapter stLgTa = new ht_stlogTableAdapter();

                            stLgTa.InsertLog(stmr.devId, stmr.devNm, stmr.onRt, stmr.offRt, stmr.OEE, stmr.prdbn, stmr.chktms,
                                Convert.ToInt16(stmr.dt.Month), Convert.ToInt16(stmr.dt.Year));
                            stmr.dt = DateTime.Now;
                        }
                        catch (Exception ex)
                        {
                            CommonClass.LogError(ex.ToString());
                        }
                        stmr.offRt = 0;
                        stmr.onRt = 0;
                        stmr.prdbn = 0;

                    }
                    else
                    {
                        stmr.dt = DateTime.Now;
                    }
                    //if(stmr)
                    if (pmmr.hswdCur < 400 && pmmr.hswdCur>0)
                    {
                        deviceState[devIndex] = '0';
                        stmr.powerSt = "0";
                        pmmr.st = "0";
                        stmr.offRt++;

                    }
                    else if (pmmr.hswdCur == null || pmmr.hswdCur==0)
                    {
                        deviceState[devIndex] = 'N';
                        stmr.powerSt = "N";
                        pmmr.st = "N";
                    }
                    else
                    {
                        deviceState[devIndex] = '1';
                        stmr.powerSt = "1";
                        pmmr.st = "1";
                        stmr.onRt++;
                    }

                    if (pmmr.ycwdCur != null)
                    {
                        if (Convert.ToDouble(dr["CntTmp"]) < pmmr.hswdCur && prdTagDict[devNm])
                        {
                            prdTagDict[devNm] = false;
                        }
                        else if (Convert.ToDouble(dr["CntTmp"]) > pmmr.hswdCur + 1 && !prdTagDict[devNm])
                        {
                            stmr.prdbn++;
                            prdTagDict[devNm] = true;
                        }
                        double ycwdMax = Convert.ToDouble(dr["ycwdMax"]);
                        double hswdMax = Convert.ToDouble(dr["hswdMax"]);

                        //后室报警判断
                        if (hswdMax>0&&pmmr.hswdCur > hswdMax && HsTagDict[devNm])
                        {
                            WaringSol(pmmr, "后室温度超过温度上限！" + "  后室温度：" + ((double)(pmmr.hswdCur)).ToString("N2") + "℃",
                                "后室上限温度：" + hswdMax.ToString("N2") + "℃", devIndex);
                            HsTagDict[devNm] = false;
                        }
                        else if (hswdMax > 0 && !HsTagDict[devNm] && pmmr.hswdCur < hswdMax)
                        {
                            HsTagDict[devNm] = true;
                        }

                        //油槽报警判断
                        if (ycwdMax>0&&pmmr.ycwdCur > ycwdMax && YcTagDict[devNm])
                        {
                            WaringSol(pmmr, "油槽温度超过温度上限！" + "  油槽温度：" + ((double)(pmmr.ycwdCur)).ToString("N2")+"℃",
                                    "油槽上限温度：" + ycwdMax.ToString("N2") + "℃", devIndex);
                            YcTagDict[devNm] = false;
                        }
                        else if (ycwdMax > 0 && pmmr.ycwdCur < ycwdMax && !HsTagDict[devNm])
                        {
                            YcTagDict[devNm] = true;
                        }
                    }
                    try
                    {
                        if (stmr.onRt == 0 && stmr.offRt == 0)
                        {
                            stmr.OEE = 0;
                        }
                        else
                        {
                            stmr.OEE = (stmr.onRt / (stmr.onRt + stmr.offRt))*100;
                        }
                    }
                    catch (DivideByZeroException)
                    {
                        stmr.OEE = 100;
                    }
                    //数据写入
                    comm.DataToDB(pmmr, stmr);
                }
                else if(msgTag)
                {
                    msgTag = false;
                    if (MessageBox.Show("设备设置发生变化，为保证数据准确请重启本软件！", "警告",
                        MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == System.Windows.Forms.DialogResult.Yes)
                    {
                        Application.Restart();
                        Application.Exit();
                    }
                }
                devIndex++;
            }
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            dataPk.Wrapper.Dispose();//回收连接
        }

        private void appexitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void Form1_MouseHover(object sender, EventArgs e)
        {
           
        }

        private void stm_autojump_CheckedChanged(object sender, EventArgs e)
        {
            if (stm_autojump.Checked)
            {
                time.Start();
                foreach (Form2 iform in lform2)
                {
                    iform.jumpEnable = true;
                }
            }
            else
            {
                time.Stop();
            }
        }

        /// <summary>
        /// 报警处理
        /// </summary>
        /// <param name="pmmr"></param>
        /// <param name="info"></param>
        /// <param name="reason"></param>
        /// <param name="devIndex"></param>
        private void WaringSol(ht_pmmr pmmr, string info, string reason,int devIndex)
        {
            string msg = pmmr.devNm + "        " + DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss") + "        " + info;
            WaringList.Invoke(
                new MethodInvoker
                (
                     delegate
                    {
                         WaringList.TopIndex = WaringList.Items.Add(msg);
                        
                         try
                         {
                             //ht_WarLogTableAdapter warlogTa = new ht_WarLogTableAdapter();
                             //warlogTa.InsertWarring(pmmr.devId, pmmr.devNm, DateTime.Now, info, reason, "", "0", "", "");
                         }
                         catch (Exception ex)
                         {
                             CommonClass.LogError(ex.ToString());
                         }
                         if (WaringList.Items.Count > 10) 
                         {
                             WaringList.Items.RemoveAt(0);
                         }
                         ////stm_autojump.CheckState = CheckState.Unchecked;
                         ////lform2[devIndex].Show();
                         ////lform2[devIndex].BringToFront();
                    }
                 )
           );

        }

        private void WaringClear_Click(object sender, EventArgs e)
        {
            WaringList.Items.Clear();
        }

    }
}
